package com.glkj.vipsystem.modules.app.controller;

import cn.hutool.core.lang.Validator;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.core.sms.aliyun.AliyunSmsTemplate;
import com.glkj.vipsystem.modules.ServiceResult;
import com.glkj.vipsystem.modules.app.annotation.LoginIgnore;
import com.glkj.vipsystem.modules.app.form.BindForm;
import com.glkj.vipsystem.modules.app.form.LoginForm;
import com.glkj.vipsystem.modules.app.utils.JwtUtils;
import com.glkj.vipsystem.service.IMemberService;
import com.glkj.vipsystem.service.ISmsCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录-短信相关API")
@RestController
@RequestMapping("/api/")
public class AppCommonController {

    @Resource
    private ISmsCodeService smsCodeService;
    @Resource
    private IMemberService memberService;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private WxMpService wxMpService;

    @LoginIgnore
    @ApiOperation("发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "类型(1-绑定)", paramType = "query", required = true)
    })
    @GetMapping("/sms/send")
    public ServiceResult<Boolean> sendSmsCode(String mobile, Integer type) {
        if (!Validator.isMobile(mobile)) {
            return ServiceResult.error("请输入正确的手机号");
        }
        if (type == null) {
            return ServiceResult.error("请选择类型");
        }

        Constant.SmsCodeType codeType = Constant.SmsCodeType.typeOf(type);
        if (codeType == null) {
            return ServiceResult.error("类型错误");
        }

        // 发送验证码 300s = 5 分钟过期
        smsCodeService.send(AliyunSmsTemplate.Bind,codeType, mobile, 300);
        return ServiceResult.ok(true);
    }

    @LoginIgnore
    @ApiOperation(value = "登录-成功返回token")
    @PostMapping("/login")
    public ServiceResult<Map<String, Object>> login(@RequestBody LoginForm form) {
        ValidatorUtils.validateEntity(form);

        // 获取openid
        try {
            WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(form.getCode());
            String openId = accessToken.getOpenId();

            // 生成token key = openid
            String token = jwtUtils.generateToken(openId);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());
            return ServiceResult.ok(map);
        } catch (WxErrorException e) {
            return ServiceResult.error("登录失败：" + e.getError().getErrorMsg());
        }
    }

//    @LoginIgnore
//    @ApiOperation(value = "登录-成功返回token")
//    @PostMapping("/loginDev")
//    public ServiceResult<Map<String, Object>> loginDev(@RequestBody LoginForm form) {
//        ValidatorUtils.validateEntity(form);
//
//        // 生成token key = openid
//        String token = jwtUtils.generateToken(form.getCode());
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("expire", jwtUtils.getExpire());
//        return ServiceResult.ok(map);
//    }

    @ApiOperation(value = "绑定手机")
    @PostMapping("/bind")
    public ServiceResult<Boolean> bind(HttpServletRequest request,@RequestBody BindForm form) {
        ValidatorUtils.validateEntity(form);
        String mobile = form.getMobile();
        if (!Validator.isMobile(mobile)) {
            return ServiceResult.error("请输入正确的手机号");
        }
        // 验证码校验
        boolean codeValidate = smsCodeService.validate(Constant.SmsCodeType.MemberBind, form.getMobile(), form.getCode());
        if (!codeValidate) {
            return ServiceResult.error("验证码错误");
        }
        String openid = (String) request.getAttribute("openid");
        memberService.bind(form,openid);
        return ServiceResult.ok(true);
    }

}
